﻿#include "forgetpasswd.h"
#include "ui_forgetpasswd.h"

#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QMessageBox>

forgetpasswd::forgetpasswd(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::forgetpasswd)
{
    ui->setupUi(this);
    net = NetworkConnect::connectserver();
    server = net->getconserver();
    connect(net, SIGNAL(findpasswd(QByteArray)), this, SLOT(handle_recv(QByteArray)));
}

forgetpasswd::~forgetpasswd()
{
    delete ui;
}

void forgetpasswd::on_pushButton_confirm_clicked()
{
    QString userid = ui->lineEdit_userid->text();
    QString answer = ui->lineEdit_answer->text();

    QJsonObject obj;
    obj.insert("command", "findpasswd");
    obj.insert("userid", userid);
    obj.insert("answer", answer);

    if(sender() == server)
    {
        ui->pushButton_cancel->setEnabled(true);
        ui->pushButton_confirm->setEnabled(true);
        ui->pushButton_confirm->setText("确认");
        ui->lineEdit_answer->setEnabled(true);
        ui->lineEdit_userid->setEnabled(true);
    }

    if(net->isServerconnected())
    {
        server->write(QJsonDocument(obj).toJson());
    }
    else
    {
        connect(server, SIGNAL(connected()), this, SLOT(on_pushButton_confirm_clicked()));
        ui->pushButton_cancel->setEnabled(false);
        ui->pushButton_confirm->setEnabled(false);
        ui->pushButton_confirm->setText("等待服务器连接中");
        ui->lineEdit_answer->setEnabled(false);
        ui->lineEdit_userid->setEnabled(false);
    }

}

void forgetpasswd::handle_recv(QByteArray mess)
{
    QJsonObject obj = QJsonDocument::fromJson(mess).object();
    if(obj.value("isallowed").toBool())
    {
        QMessageBox::information(this, "成功", "你的密码是" + obj.value("passwd").toString());
    }
    else
    {
        QMessageBox::information(this, "失败", "错误原因" + obj.value("errmessage").toString());
    }
}


void forgetpasswd::on_pushButton_cancel_clicked()
{
    this->close();
}

